<?php
// 加载通用文件
require_once __DIR__ . '/../common/autoload.php';

// 检查是否已安装
if (!file_exists(__DIR__ . '/../.installed') && basename($_SERVER['PHP_SELF']) !== 'install.php') {
    header('Location: /install.php');
    exit;
}

// 修改查询，仅包含制作中和请取餐的订单
$orders = Database::fetchAll("SELECT o.queue_number, o.status, o.updated_at, o.user_id 
                             FROM orders o
                             WHERE o.status IN ('cooking', 'completed') 
                             AND DATE(o.created_at) = CURDATE()
                             ORDER BY 
                                CASE 
                                    WHEN o.status = 'completed' THEN 2
                                    WHEN o.status = 'cooking' THEN 1
                                END ASC,
                                o.created_at ASC
                             LIMIT 50");
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>排队显示屏</title>
    <!-- CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.3/css/all.min.css">
    <link rel="stylesheet" href="/assets/css/style.css">
    <style>
        @keyframes blink {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        
        body {
            background-color: #f8f9fa;
            padding: 0;
            margin: 0;
            overflow: hidden;
        }
        
        .queue-container {
            height: 100vh;
            overflow: hidden;
            padding: 10px;
            display: flex;
            flex-direction: column;
        }
        
        .queue-section {
            margin-bottom: 10px;
            flex: 1;
            display: flex;
            flex-direction: column;
            min-height: 0; /* 修复Flex布局溢出问题 */
        }
        
        .queue-section h2 {
            color: var(--primary-color);
            font-size: 28px;
            margin-bottom: 10px;
            padding-bottom: 8px;
            border-bottom: 2px solid var(--primary-color);
            text-align: center;
        }
        
        .queue-items {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            justify-content: center;
            overflow-y: auto;
            flex: 1;
            padding: 5px;
        }
        
        .queue-item {
            width: 130px;
            height: 130px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
            transition: all 0.3s;
            margin-bottom: 10px;
        }
        
        .queue-item.member {
            border: 3px solid gold !important;
            box-shadow: 0 4px 12px rgba(255,215,0,0.5);
        }
        
        .queue-item-number {
            font-size: 42px;
            font-weight: bold;
        }
        
        .queue-item-status {
            margin-top: 8px;
            font-size: 16px;
            padding: 3px 10px;
            border-radius: 15px;
            color: white;
            font-weight: bold;
        }
        
        .queue-item.cooking {
            background-color: #fff;
            border: 2px solid #3498db;
            animation: blink 2s infinite;
        }
        
        .queue-item.cooking .queue-item-number {
            color: #3498db;
        }
        
        .queue-item.cooking .queue-item-status {
            background-color: #3498db;
        }
        
        .queue-item.completed {
            background-color: #fff;
            border: 2px solid #2ecc71;
            animation: blink 1.5s infinite;
        }
        
        .queue-item.completed .queue-item-number {
            color: #2ecc71;
        }
        
        .queue-item.completed .queue-item-status {
            background-color: #2ecc71;
        }
        
        /* 分隔线 */
        .divider {
            width: 100%;
            height: 1px;
            background-color: #ddd;
            margin: 10px 0;
        }
        
        /* 响应式设计增强 */
        @media (max-width: 768px) {
            .queue-section h2 {
                font-size: 24px;
                margin-bottom: 8px;
                padding-bottom: 5px;
            }
            
            .queue-item {
                width: 100px;
                height: 100px;
                margin-bottom: 8px;
            }
            
            .queue-item-number {
                font-size: 32px;
            }
            
            .queue-item-status {
                font-size: 14px;
                padding: 2px 8px;
            }
            
            .queue-items {
                gap: 8px;
                padding: 3px;
            }
            
            .divider {
                margin: 5px 0;
            }
        }
        
        /* 更小屏幕的优化 */
        @media (max-width: 480px) {
            .queue-container {
                padding: 5px;
            }
            
            .queue-section h2 {
                font-size: 20px;
            }
            
            .queue-item {
                width: 90px;
                height: 90px;
            }
            
            .queue-item-number {
                font-size: 28px;
            }
            
            .queue-item-status {
                font-size: 12px;
                padding: 2px 6px;
            }
        }
    </style>
</head>
<body>
    <div class="queue-container">
        <!-- 制作中区域 -->
        <div class="queue-section">
            <h2><i class="fas fa-spinner fa-spin"></i> 制作中</h2>
            <div class="queue-items">
                <?php 
                $cooking_orders = array_filter($orders, function($order) {
                    return $order['status'] === 'cooking';
                });
                
                if (empty($cooking_orders)): 
                ?>
                    <div class="alert alert-info w-100">暂无制作中的订单</div>
                <?php else: ?>
                    <?php foreach ($cooking_orders as $order): ?>
                        <div class="queue-item cooking <?php echo !empty($order['user_id']) ? 'member' : ''; ?>">
                            <div class="queue-item-number"><?php echo $order['queue_number']; ?></div>
                            <div class="queue-item-status">制作中</div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="divider"></div>
        
        <!-- 已取餐区域 -->
        <div class="queue-section">
            <h2><i class="fas fa-shopping-bag"></i> 请取餐</h2>
            <div class="queue-items">
                <?php 
                $completed_orders = array_filter($orders, function($order) {
                    return $order['status'] === 'completed';
                });
                
                if (empty($completed_orders)): 
                ?>
                    <div class="alert alert-info w-100">暂无请取餐的订单</div>
                <?php else: ?>
                    <?php foreach ($completed_orders as $order): ?>
                        <div class="queue-item completed <?php echo !empty($order['user_id']) ? 'member' : ''; ?>">
                            <div class="queue-item-number"><?php echo $order['queue_number']; ?></div>
                            <div class="queue-item-status">请取餐</div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 刷新页面函数
        function refreshPage() {
            console.log("刷新页面...");
            window.location.reload();
        }
        
        // 用于跟踪是否有待处理的刷新
        let pendingRefresh = false;
        let refreshTimer = null;
        
        // 请求刷新，但避免频繁重复刷新
        function requestRefresh(delay = 0) {
            if (pendingRefresh) return; // 已经有待处理的刷新，忽略此次请求
            
            pendingRefresh = true;
            clearTimeout(refreshTimer);
            
            if (delay > 0) {
                console.log(`将在 ${delay}ms 后刷新页面...`);
                refreshTimer = setTimeout(refreshPage, delay);
            } else {
                refreshPage(); // 立即刷新
            }
        }
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log("页面加载完成，初始化...");
            
            // 设置默认自动刷新（每5秒刷新一次）
            console.log("设置自动刷新计时器...");
            const autoRefreshInterval = setInterval(() => requestRefresh(), 5000);
            
            try {
                // 创建WebSocket连接
                console.log("初始化WebSocket连接...");
                
                // 获取当前主机名和协议
                const hostname = window.location.hostname || "localhost";
                const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
                const wsUrl = `${wsProtocol}//${hostname}:8080`;
                
                console.log(`尝试连接到WebSocket服务器: ${wsUrl}`);
                const ws = new WebSocket(wsUrl);
                
                // 设置连接超时
                const connectionTimeout = setTimeout(() => {
                    console.error("WebSocket连接超时");
                }, 5000);
                
                // 连接建立
                ws.onopen = function() {
                    console.log("WebSocket连接已建立");
                    clearTimeout(connectionTimeout);
                    
                    // 注册客户端类型为排队显示屏
                    try {
                        const registerMsg = {
                            type: 'register',
                            client_type: 'queue'
                        };
                        ws.send(JSON.stringify(registerMsg));
                        console.log("已发送注册消息");
                    } catch (error) {
                        console.error("发送注册消息失败:", error);
                    }
                    
                    // 发送一个初始心跳
                    try {
                        ws.send(JSON.stringify({ type: 'ping', timestamp: Date.now() }));
                        console.log("已发送初始心跳");
                    } catch (error) {
                        console.error("发送初始心跳失败:", error);
                    }
                };
                
                // 收到消息
                ws.onmessage = function(event) {
                    try {
                        if (typeof event.data !== 'string' || !event.data.trim()) {
                            console.warn("收到无效WebSocket消息:", event.data);
                            return;
                        }
                        
                        const data = JSON.parse(event.data);
                        console.log("收到WebSocket消息:", data.type);
                        
                        // 根据消息类型处理
                        switch (data.type) {
                            case 'register_success':
                                console.log("注册成功:", data.message);
                                break;
                                
                            case 'pong':
                                // 心跳响应，不做处理
                                console.log("收到心跳响应");
                                break;
                                
                            case 'order_new':
                                console.log("收到新订单通知");
                                requestRefresh(300); // 更短的延迟刷新，确保数据已更新但显示更及时
                                break;
                                
                            case 'order_status':
                                console.log("收到订单状态更新");
                                // 订单状态变更，立即刷新显示
                                if (data.order && data.order.status) {
                                    console.log("订单状态更新为:", data.order.status);
                                    // 如果是重要状态变更（如已取餐），立即刷新
                                    if (data.order.status === 'completed') {
                                        console.log("订单待取餐，立即刷新");
                                        requestRefresh(100); // 更快速刷新
                                    } else {
                                        requestRefresh(300); // 标准延迟刷新
                                    }
                                } else {
                                    requestRefresh(300); // 标准延迟刷新
                                }
                                break;
                                
                            default:
                                console.warn("未知消息类型:", data.type);
                                break;
                        }
                    } catch (error) {
                        console.error("处理WebSocket消息失败:", error);
                    }
                };
                
                // 连接关闭
                ws.onclose = function(event) {
                    console.log("WebSocket连接已关闭", event.code, event.reason);
                    
                    // 缩短自动刷新间隔以弥补WebSocket断开
                    clearInterval(autoRefreshInterval);
                    console.log("WebSocket连接断开，切换到更频繁的自动刷新");
                    setInterval(() => requestRefresh(), 5000); // 每5秒刷新一次
                };
                
                // 连接错误
                ws.onerror = function(error) {
                    console.error("WebSocket连接错误:", error);
                };
                
                // 设置心跳定时器
                console.log("设置WebSocket心跳...");
                const heartbeatInterval = setInterval(() => {
                    if (ws.readyState === WebSocket.OPEN) {
                        try {
                            ws.send(JSON.stringify({ type: 'ping', timestamp: Date.now() }));
                            console.log("已发送心跳");
                        } catch (error) {
                            console.error("发送心跳失败:", error);
                            clearInterval(heartbeatInterval);
                        }
                    } else if (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) {
                        console.log("WebSocket已关闭，停止心跳");
                        clearInterval(heartbeatInterval);
                    }
                }, 20000); // 每20秒发送一次心跳
                
            } catch (error) {
                console.error("初始化WebSocket失败:", error);
                
                // 只使用自动刷新
                console.log("使用纯自动刷新模式");
            }
        });
    </script>
</body>
</html> 